package com.cskaoyan._14network._02udp.chattest;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author Macro_Ray
 * @since 2024/3/25 22:10
 */
public class Reveive {
    public static void main(String[] args) throws IOException {
        // 1.创建DatagramSocket对象
        DatagramSocket ds = new DatagramSocket(8888);


        // 2.接收数据
        byte[] buf = new byte[1024];
        DatagramPacket dp = new DatagramPacket(buf, buf.length);

        ds.receive(dp);

        // 3.解析数据
        byte[] data = dp.getData();
        int len = dp.getLength();
        InetAddress address = dp.getAddress();
        int port = dp.getPort();

        System.out.println("接收到数据：" + new String(data, 0, len));
        System.out.println("来自：" + address + ":" + port);

        // 4.释放资源
        ds.close();

    }
}
